package frames;

import com.ap.logic.Classification.Category;
import com.ap.logic.Classification.Classification;
import com.ap.logic.xml.ReadWriteClassificationXML;
import com.ap.logic.Classification.Class;
import com.ap.logic.Classification.ClassificationItem;
import com.ap.logic.QuizClasses.Question;
import com.ap.logic.QuizClasses.Quiz;
import com.ap.logic.QuizClasses.QuizResult;
import com.ap.configuration.Config;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Random;

import java.util.Set;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.ScrollPaneLayout;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
/**

 * @author olia
 */
public class QuestionerJFrame extends JFrame {

    /**
     * Creates new form QuestionerJFrame
     */
    public QuestionerJFrame() {
        initComponents();


        // read configuration , and set static variables in Config class
        //Config.classificationXMLPath=...
        //Config.questionsPath=....

        
        //now create tree with all available categories
        createCategoriesTree();

        final JLabel infoLabel=this.ClassificationItemInfoLabel;
        final JTextArea infoArea=this.classificationItemInfoTextArea;
                    // add listener , to show info about selected category
                    classificationTree.addTreeSelectionListener(new TreeSelectionListener() {
                        public void valueChanged(TreeSelectionEvent e) {
                            DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                                       classificationTree.getLastSelectedPathComponent();

                                /* if nothing is selected */
                                if (node == null ) return;
                                if(!( node.getUserObject() instanceof ClassificationItem)  ) return ;
                                ClassificationItem  nodeObject =(ClassificationItem) node.getUserObject();
                                    infoLabel.setText("");
                                    infoArea.setText("");

                                    infoLabel.setText(nodeObject.getName());
                                    infoArea.setText(infoArea.getText()+"ID : " +nodeObject.getId()+"\n");
                                    infoArea.setText(infoArea.getText()+"Number Of Questions  : " +nodeObject.getnOfQuestions()+"\n");
                                    infoArea.setText(infoArea.getText()+"Number Of Subcategories : " +nodeObject.getnOfSubcategories()+"\n");
                            }
                        }
                    );

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        categoryTreePopupMenu = new javax.swing.JPopupMenu();
        addCategoryItem = new javax.swing.JMenuItem();
        removeCategoryItem = new javax.swing.JMenuItem();
        addClassItem = new javax.swing.JMenuItem();
        showInfoItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        addQuestion = new javax.swing.JMenuItem();
        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        quizPanel = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        quizQuestionTextTextPane = new javax.swing.JTextPane();
        quizVariantsPanel = new javax.swing.JPanel();
        quizVariant0RadioButton = new javax.swing.JRadioButton();
        quizVariant1RadioButton = new javax.swing.JRadioButton();
        quizVariant2RadioButton = new javax.swing.JRadioButton();
        quizVariant3RadioButton = new javax.swing.JRadioButton();
        quizYesRadioButton = new javax.swing.JRadioButton();
        quizNoRadioButton = new javax.swing.JRadioButton();
        quizScrollPane = new javax.swing.JScrollPane();
        quizQuestionsBrowserPanel = new javax.swing.JPanel();
        prevQuestionButton = new javax.swing.JButton();
        nextQuestionButton = new javax.swing.JButton();
        quizFinishButton = new javax.swing.JButton();
        quizSetupPanel = new javax.swing.JPanel();
        timeLabel = new javax.swing.JLabel();
        includeDetailedAnwersLabel = new javax.swing.JLabel();
        quizMinutesTextField = new javax.swing.JTextField();
        startQuizButton = new javax.swing.JButton();
        questionsCountLabel = new javax.swing.JLabel();
        quizQuestionsCountTextField = new javax.swing.JTextField();
        quizTopicsLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        quizTopicsTextPane = new javax.swing.JTextPane();
        quizIncludeDetailedAnswersCheckBox = new javax.swing.JCheckBox();
        includeTipsLabel = new javax.swing.JLabel();
        quizIncludeTipsCheckBox = new javax.swing.JCheckBox();
        leftPanel = new javax.swing.JPanel();
        paneWithTree = new javax.swing.JScrollPane();
        classificationTree = new javax.swing.JTree();
        statisticPanel = new javax.swing.JPanel();
        ClassificationItemInfoLabel = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        classificationItemInfoTextArea = new javax.swing.JTextArea();
        quizReviewPanel = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        quizReviewTextPane = new javax.swing.JTextPane();
        questionerMenuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        exit = new javax.swing.JMenuItem();
        quizMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        helpMenuItem = new javax.swing.JMenuItem();

        addCategoryItem.setText("Add Category");
        addCategoryItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addCategoryItemActionPerformed(evt);
            }
        });
        categoryTreePopupMenu.add(addCategoryItem);

        removeCategoryItem.setText("Remove Category");
        removeCategoryItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeCategoryItemActionPerformed(evt);
            }
        });
        categoryTreePopupMenu.add(removeCategoryItem);

        addClassItem.setText("Add Class");
        addClassItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addClassItemActionPerformed(evt);
            }
        });
        categoryTreePopupMenu.add(addClassItem);

        showInfoItem.setText("Show Info");
        showInfoItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showInfoItemActionPerformed(evt);
            }
        });
        categoryTreePopupMenu.add(showInfoItem);
        categoryTreePopupMenu.add(jSeparator1);

        addQuestion.setText("ADD Question");
        addQuestion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addQuestionActionPerformed(evt);
            }
        });
        categoryTreePopupMenu.add(addQuestion);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Questioner 0.0"); // NOI18N
        setBackground(new java.awt.Color(204, 0, 0));
        setMinimumSize(new java.awt.Dimension(650, 500));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        quizPanel.setBackground(new java.awt.Color(204, 204, 204));
        quizPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Quiz", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, java.awt.Color.black));

        jScrollPane2.setViewportView(quizQuestionTextTextPane);

        buttonGroup1.add(quizVariant0RadioButton);
        quizVariant0RadioButton.setText("Variant 1");

        buttonGroup1.add(quizVariant1RadioButton);
        quizVariant1RadioButton.setText("Variant 2");

        buttonGroup1.add(quizVariant2RadioButton);
        quizVariant2RadioButton.setText("Variant 3");

        buttonGroup1.add(quizVariant3RadioButton);
        quizVariant3RadioButton.setText("Variant 4");

        buttonGroup2.add(quizYesRadioButton);
        quizYesRadioButton.setText("Yes");

        buttonGroup2.add(quizNoRadioButton);
        quizNoRadioButton.setText("No");

        javax.swing.GroupLayout quizVariantsPanelLayout = new javax.swing.GroupLayout(quizVariantsPanel);
        quizVariantsPanel.setLayout(quizVariantsPanelLayout);
        quizVariantsPanelLayout.setHorizontalGroup(
            quizVariantsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(quizVariantsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(quizVariantsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(quizVariantsPanelLayout.createSequentialGroup()
                        .addComponent(quizVariant0RadioButton)
                        .addGap(18, 18, 18)
                        .addComponent(quizVariant1RadioButton)
                        .addGap(18, 18, 18)
                        .addComponent(quizVariant2RadioButton)
                        .addGap(18, 18, 18)
                        .addComponent(quizVariant3RadioButton))
                    .addGroup(quizVariantsPanelLayout.createSequentialGroup()
                        .addComponent(quizYesRadioButton)
                        .addGap(18, 18, 18)
                        .addComponent(quizNoRadioButton)))
                .addContainerGap(258, Short.MAX_VALUE))
        );
        quizVariantsPanelLayout.setVerticalGroup(
            quizVariantsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(quizVariantsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(quizVariantsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(quizVariant0RadioButton)
                    .addComponent(quizVariant1RadioButton)
                    .addComponent(quizVariant2RadioButton)
                    .addComponent(quizVariant3RadioButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(quizVariantsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(quizYesRadioButton)
                    .addComponent(quizNoRadioButton))
                .addContainerGap())
        );

        quizQuestionsBrowserPanel.setAutoscrolls(true);

        javax.swing.GroupLayout quizQuestionsBrowserPanelLayout = new javax.swing.GroupLayout(quizQuestionsBrowserPanel);
        quizQuestionsBrowserPanel.setLayout(quizQuestionsBrowserPanelLayout);
        quizQuestionsBrowserPanelLayout.setHorizontalGroup(
            quizQuestionsBrowserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 590, Short.MAX_VALUE)
        );
        quizQuestionsBrowserPanelLayout.setVerticalGroup(
            quizQuestionsBrowserPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 58, Short.MAX_VALUE)
        );

        quizScrollPane.setViewportView(quizQuestionsBrowserPanel);

        prevQuestionButton.setText("Previous Question");
        prevQuestionButton.setToolTipText("");
        prevQuestionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                prevQuestionButtonActionPerformed(evt);
            }
        });

        nextQuestionButton.setText("Next Question");
        nextQuestionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextQuestionButtonActionPerformed(evt);
            }
        });

        quizFinishButton.setBackground(new java.awt.Color(255, 255, 102));
        quizFinishButton.setText("Finish test");
        quizFinishButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quizFinishButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout quizPanelLayout = new javax.swing.GroupLayout(quizPanel);
        quizPanel.setLayout(quizPanelLayout);
        quizPanelLayout.setHorizontalGroup(
            quizPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(quizPanelLayout.createSequentialGroup()
                .addGroup(quizPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(quizPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(quizPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(quizVariantsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(quizScrollPane)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)))
                    .addGroup(quizPanelLayout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addComponent(prevQuestionButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(nextQuestionButton)
                        .addGap(37, 37, 37)
                        .addComponent(quizFinishButton, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        quizPanelLayout.setVerticalGroup(
            quizPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, quizPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE)
                .addGap(78, 78, 78)
                .addComponent(quizVariantsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addGroup(quizPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(prevQuestionButton)
                    .addComponent(nextQuestionButton)
                    .addComponent(quizFinishButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(quizScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        quizSetupPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("New Quiz Setup"));

        timeLabel.setText("Time(min)");

        includeDetailedAnwersLabel.setText("Detailed Ans Questions");

        quizMinutesTextField.setText("20");

        startQuizButton.setText("Start Quiz");
        startQuizButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startQuizButtonActionPerformed(evt);
            }
        });

        questionsCountLabel.setText("Quistions Count");

        quizQuestionsCountTextField.setText("10");

        quizTopicsLabel.setText("Quiz Topics");

        quizTopicsTextPane.setFont(new java.awt.Font("Tahoma", 0, 10));
        jScrollPane1.setViewportView(quizTopicsTextPane);

        includeTipsLabel.setText("Include TIPS");

        javax.swing.GroupLayout quizSetupPanelLayout = new javax.swing.GroupLayout(quizSetupPanel);
        quizSetupPanel.setLayout(quizSetupPanelLayout);
        quizSetupPanelLayout.setHorizontalGroup(
            quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(quizSetupPanelLayout.createSequentialGroup()
                .addGap(104, 104, 104)
                .addGroup(quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(timeLabel)
                    .addComponent(quizTopicsLabel)
                    .addComponent(questionsCountLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
                    .addComponent(startQuizButton, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(quizSetupPanelLayout.createSequentialGroup()
                        .addGroup(quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(quizQuestionsCountTextField)
                            .addComponent(quizMinutesTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 375, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, quizSetupPanelLayout.createSequentialGroup()
                        .addComponent(includeDetailedAnwersLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(quizIncludeDetailedAnswersCheckBox)
                        .addGap(18, 18, 18)
                        .addComponent(includeTipsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(quizIncludeTipsCheckBox)))
                .addContainerGap())
        );
        quizSetupPanelLayout.setVerticalGroup(
            quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(quizSetupPanelLayout.createSequentialGroup()
                .addGroup(quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(timeLabel)
                    .addComponent(quizMinutesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(questionsCountLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(quizQuestionsCountTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(quizTopicsLabel)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(includeTipsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                    .addGroup(quizSetupPanelLayout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addGroup(quizSetupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(includeDetailedAnwersLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(quizIncludeDetailedAnswersCheckBox)))
                    .addComponent(quizIncludeTipsCheckBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(49, 49, 49)
                .addComponent(startQuizButton))
        );

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        classificationTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        classificationTree.setRootVisible(false);
        classificationTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                classificationTreeMouseClicked(evt);
            }
        });
        paneWithTree.setViewportView(classificationTree);

        statisticPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Info"));

        ClassificationItemInfoLabel.setFont(new java.awt.Font("Tahoma", 1, 12));

        classificationItemInfoTextArea.setBackground(new java.awt.Color(212, 208, 200));
        classificationItemInfoTextArea.setColumns(20);
        classificationItemInfoTextArea.setEditable(false);
        classificationItemInfoTextArea.setRows(5);
        jScrollPane4.setViewportView(classificationItemInfoTextArea);

        javax.swing.GroupLayout statisticPanelLayout = new javax.swing.GroupLayout(statisticPanel);
        statisticPanel.setLayout(statisticPanelLayout);
        statisticPanelLayout.setHorizontalGroup(
            statisticPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statisticPanelLayout.createSequentialGroup()
                .addGroup(statisticPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(statisticPanelLayout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(ClassificationItemInfoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(statisticPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 392, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(22, Short.MAX_VALUE))
        );
        statisticPanelLayout.setVerticalGroup(
            statisticPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statisticPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ClassificationItemInfoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(196, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout leftPanelLayout = new javax.swing.GroupLayout(leftPanel);
        leftPanel.setLayout(leftPanelLayout);
        leftPanelLayout.setHorizontalGroup(
            leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(leftPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(leftPanelLayout.createSequentialGroup()
                        .addComponent(statisticPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(paneWithTree, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)))
        );
        leftPanelLayout.setVerticalGroup(
            leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, leftPanelLayout.createSequentialGroup()
                .addComponent(paneWithTree, javax.swing.GroupLayout.DEFAULT_SIZE, 477, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statisticPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        quizReviewPanel.setBackground(new java.awt.Color(200, 202, 195));

        jScrollPane3.setViewportView(quizReviewTextPane);

        javax.swing.GroupLayout quizReviewPanelLayout = new javax.swing.GroupLayout(quizReviewPanel);
        quizReviewPanel.setLayout(quizReviewPanelLayout);
        quizReviewPanelLayout.setHorizontalGroup(
            quizReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(quizReviewPanelLayout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE)
                .addGap(106, 106, 106))
        );
        quizReviewPanelLayout.setVerticalGroup(
            quizReviewPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(quizReviewPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane3)
                .addGap(99, 99, 99))
        );

        fileMenu.setText("File");
        fileMenu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                fileMenuMouseClicked(evt);
            }
        });

        exit.setText("Exit");
        exit.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                exitMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                exitMouseEntered(evt);
            }
        });
        exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitActionPerformed(evt);
            }
        });
        exit.addMenuKeyListener(new javax.swing.event.MenuKeyListener() {
            public void menuKeyPressed(javax.swing.event.MenuKeyEvent evt) {
                exitMenuKeyPressed(evt);
            }
            public void menuKeyReleased(javax.swing.event.MenuKeyEvent evt) {
            }
            public void menuKeyTyped(javax.swing.event.MenuKeyEvent evt) {
            }
        });
        fileMenu.add(exit);

        questionerMenuBar.add(fileMenu);

        quizMenu.setText("Quiz");

        jMenuItem1.setText("New Quiz");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        quizMenu.add(jMenuItem1);

        questionerMenuBar.add(quizMenu);

        helpMenu.setText("Help");

        helpMenuItem.setText("About");
        helpMenu.add(helpMenuItem);

        questionerMenuBar.add(helpMenu);

        setJMenuBar(questionerMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(leftPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(quizReviewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(quizPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(quizSetupPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(quizSetupPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(quizPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(quizReviewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(leftPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents




    private void classificationTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_classificationTreeMouseClicked
         javax.swing.JTree tree = (JTree) evt.getSource(); // get tree component

         TreePath tp = tree.getPathForLocation(evt.getX(), evt.getY()); // get path as [root, subnode ,subnode ..]
   
         if (tp != null){
                    // if we click on some node
                    System.out.println(tp.toString());
         }
         if(tp==null) return ;

         DefaultMutableTreeNode node = (DefaultMutableTreeNode) tp.getLastPathComponent();

         if(  evt.getClickCount()==2){
                // dont add dublicates

                if(this.quiz!=null){
                    this.addCategoryOrClassToQuiz((ClassificationItem)node.getUserObject(), quiz);
                    //  if(this.quizTopicsTextPane.getText().indexOf(node.getUserObject().toString())<0)
                    // this.quizTopicsTextPane.setText(this.quizTopicsTextPane.getText()+node.getUserObject()+"\n");
                    return ;
                }
         }

      if(SwingUtilities.isRightMouseButton(evt)){
             if(tp.toString().equals("[root]")){
                      categoryTreePopupMenu.removeAll();   
                      categoryTreePopupMenu.add(this.addClassItem);
                      categoryTreePopupMenu.show(evt.getComponent(), evt.getX(), evt.getY());

                                    classificationTree.setSelectionPath(tp);
                                    classificationTree.scrollPathToVisible(tp);
             }else {
                                    categoryTreePopupMenu.removeAll();
                                    categoryTreePopupMenu.add(this.addCategoryItem);
                                    
                                    if( ((DefaultMutableTreeNode)tp.getLastPathComponent()).getUserObject() instanceof Category){
                                        categoryTreePopupMenu.add(this.removeCategoryItem);
                                    }
                                    
                                    categoryTreePopupMenu.add(this.jSeparator1);
                                    categoryTreePopupMenu.add(this.addQuestion);
                                    categoryTreePopupMenu.show(evt.getComponent(), evt.getX(), evt.getY());

                                    classificationTree.setSelectionPath(tp);
                                    classificationTree.scrollPathToVisible(tp);
                    }
      }
    }//GEN-LAST:event_classificationTreeMouseClicked

    private void fileMenuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_fileMenuMouseClicked
    }//GEN-LAST:event_fileMenuMouseClicked

    private void exitMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exitMouseClicked
    }//GEN-LAST:event_exitMouseClicked

    private void exitMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_exitMouseEntered
    }//GEN-LAST:event_exitMouseEntered

    private void exitMenuKeyPressed(javax.swing.event.MenuKeyEvent evt) {//GEN-FIRST:event_exitMenuKeyPressed

    }//GEN-LAST:event_exitMenuKeyPressed

    private void exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitActionPerformed
        dispose();
        System.exit(0);
    }//GEN-LAST:event_exitActionPerformed

    private void addCategoryItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addCategoryItemActionPerformed

        TreePath tp = classificationTree.getSelectionPath(); // get path as [root, subnode ,subnode ..]
        DefaultMutableTreeNode  currCategoryNode = (DefaultMutableTreeNode) tp.getLastPathComponent();
        DefaultTreeModel model = (DefaultTreeModel) classificationTree.getModel();

        NewCategoryDialog dialog=new NewCategoryDialog(this, true);
        dialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
        String newCategoryName=dialog.getNameOfCategoryDialog();
        Boolean newCategoryFile=dialog.getFileOfCategoryDialog();

        if(newCategoryName==null || newCategoryName.length()==0 ) return ;

        Category newCategory=new Category();
        newCategory.setId(((ClassificationItem)currCategoryNode.getUserObject()).getId()+"_"+currCategoryNode.getChildCount() );
        newCategory.setName(newCategoryName);
        newCategory.setnOfQuestions(0);
        newCategory.setnOfSubcategories(0);
        if(newCategoryFile  ){
            newCategory.setFileName(newCategoryName.replace(" ", "").toLowerCase() +".xml");
            // create new file for category if needed
            this.reader.addQuestionsFile(this.dataPath+newCategory.getFileName(), newCategory);
        }else{
            newCategory.setFileName(null);
        }

        // add to classification tree
        model.insertNodeInto(new DefaultMutableTreeNode(newCategory), currCategoryNode, currCategoryNode.getChildCount());

        // add to classification.xml  file
        this.reader.addCategoryToXML(newCategory,this.classificationXMLPath,
                ((ClassificationItem)currCategoryNode.getUserObject()).getId());

    }//GEN-LAST:event_addCategoryItemActionPerformed

    private void showInfoItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showInfoItemActionPerformed
        JOptionPane.showMessageDialog(null, "Show info about selected item");
    }//GEN-LAST:event_showInfoItemActionPerformed

    private void addQuestionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addQuestionActionPerformed

         Category categoryForNewQuestion=((Category)  ((DefaultMutableTreeNode)  classificationTree.
                                                getSelectionPath().getLastPathComponent()).getUserObject());

         DefaultMutableTreeNode  parentOfCategoryForNewQuestion=(DefaultMutableTreeNode)   ((DefaultMutableTreeNode)  classificationTree.
                                                getSelectionPath().getLastPathComponent()).getParent();         

        NewQuestionDialog dialog=new NewQuestionDialog(this, true);
        dialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        dialog.setNewQuestionCategory(   categoryForNewQuestion  );
        dialog.setVisible(true);

        if(dialog.getDialogResult()){
            categoryForNewQuestion.setnOfQuestions(categoryForNewQuestion.getnOfQuestions()+1);
            this.reader.updateQuestionsCountInXML(categoryForNewQuestion, 1);

            //update tree number of questions
            while( parentOfCategoryForNewQuestion.getUserObject() instanceof   ClassificationItem ){
                ClassificationItem item=(ClassificationItem) parentOfCategoryForNewQuestion.getUserObject();
                item.setnOfQuestions(item.getnOfQuestions()+1);
            
                parentOfCategoryForNewQuestion=(DefaultMutableTreeNode) parentOfCategoryForNewQuestion.getParent();
            }

        }
        
    }//GEN-LAST:event_addQuestionActionPerformed

    private void addClassItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClassItemActionPerformed
        JOptionPane.showMessageDialog(null, "Adding class");
    }//GEN-LAST:event_addClassItemActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed

        this.quiz=new Quiz();
        this.quizMinutesTextField.setText(this.quiz.getMinutes()+"");
        this.quizQuestionsCountTextField.setText(this.quiz.getNofquestions()+"");
        this.quizTopicsTextPane.setText("");
        this.quizIncludeDetailedAnswersCheckBox.setSelected(this.quiz.getIncludeDetailedAnswersQuestions());
        this.quizIncludeTipsCheckBox.setSelected(this.quiz.getIncludeTips());
        
        this.quizSetupPanel.setVisible(true);
        this.quizPanel.setVisible(false);
        this.quizReviewPanel.setVisible(false);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        this.quizSetupPanel.setVisible(false);
        this.quizPanel.setVisible(false);
        this.quizReviewPanel.setVisible(false);
    }//GEN-LAST:event_formWindowOpened

    private void startQuizButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startQuizButtonActionPerformed

        if(this.quiz.getCategories().size()>0){
                // configure quiz , set time , number of questions , and generate questions
                this.quiz.setMinutes(  Integer.parseInt(this.quizMinutesTextField.getText())  );
                this.quiz.setNofquestions(  Integer.parseInt( this.quizQuestionsCountTextField.getText()) );
                this.quiz.setIncludeDetailedAnswersQuestions(this.quizIncludeDetailedAnswersCheckBox.isSelected());
                this.quiz.setIncludeTips(this.quizIncludeTipsCheckBox.isSelected());
                this.quiz.generateQuestions();
                this.quiz.getAnswers().clear();


                // hide quiz configuration , and display quiz panel
                this.quizSetupPanel.setVisible(false);
                this.quizPanel.setVisible(true);

                this.runQuiz();
        }else{
                JOptionPane.showMessageDialog(this, "Add some categories to quiz , by double clicking on category in the tree");
        }
    }//GEN-LAST:event_startQuizButtonActionPerformed

    private void removeCategoryItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeCategoryItemActionPerformed
        JOptionPane.showMessageDialog(this, "removing category ");
        this.reader.removeCategoryFromXML(null, null, null);// removing category
        // and we need to remove it from tree
    }//GEN-LAST:event_removeCategoryItemActionPerformed

    private void nextQuestionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextQuestionButtonActionPerformed
         saveAnswer();

         this.quiz.getNextQuestion();
         activateDeactivateNextPrevBrowseButtons();
         ShowQuestionAndshowVariants(null);  
    }//GEN-LAST:event_nextQuestionButtonActionPerformed

    private void prevQuestionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_prevQuestionButtonActionPerformed
         saveAnswer();

         this.quiz.getPreviousQuestion();
               activateDeactivateNextPrevBrowseButtons();
               ShowQuestionAndshowVariants(null);
    }//GEN-LAST:event_prevQuestionButtonActionPerformed

    private void quizFinishButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quizFinishButtonActionPerformed
        saveAnswer();// save last answer
        QuizResult result=new QuizResult();
        result.setQuiz(this.quiz);
        result.checkQuiz();

        this.quizPanel.setVisible(false);
        this.quizReviewPanel.setVisible(true);
        
        JOptionPane.showMessageDialog(this, "Correct Answers "+result.getCorrectAnswers());
        showCorrectAndWrongAnswers(result);
    }//GEN-LAST:event_quizFinishButtonActionPerformed


    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                } 
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(QuestionerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(QuestionerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(QuestionerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(QuestionerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new QuestionerJFrame().setVisible(true);
            }
        });
    }

    private void createCategoriesTree() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");

        this.classification = this.reader.getClassification(this.classificationXMLPath);

        Set<String> classesNames = this.classification.getClasses().keySet();

        for (String item : classesNames) {
            DefaultMutableTreeNode curClassNode = new DefaultMutableTreeNode(this.classification.getClasses().get(item));

            LinkedHashMap<String, Category> categoriesInCurrClass = this.classification.getClasses().get(item).getCategories();
            Set<String> categoriesInCurrClassKeys = categoriesInCurrClass.keySet();

            for (String catKey : categoriesInCurrClassKeys) {
                DefaultMutableTreeNode curCategoryNode = new DefaultMutableTreeNode(categoriesInCurrClass.get(catKey));

                addCategoriesToClassRecursive(categoriesInCurrClass.get(catKey), curCategoryNode);
                curClassNode.add(curCategoryNode);
            }

            root.add(curClassNode);
            
        }
      
        classificationTree.setModel(new javax.swing.tree.DefaultTreeModel(root));
        classificationTree.setRootVisible(true);
        classificationTree.setShowsRootHandles(true);

        paneWithTree.add(classificationTree);
        paneWithTree.setViewportView(classificationTree);
    }

    private void addCategoriesToClassRecursive(Category curCategory, DefaultMutableTreeNode curCategoryNode) {
        if (curCategory.getCategories().size() == 0) {
            return;
        }
        
        LinkedHashMap<String, Category> categoriesInCurrCategory = curCategory.getCategories();
        Set<String> curCategoryKeys = curCategory.getCategories().keySet();

        for (String curCategoryKey : curCategoryKeys) {
            DefaultMutableTreeNode categoryNodeToAdd = new DefaultMutableTreeNode(categoriesInCurrCategory.get(curCategoryKey));

            addCategoriesToClassRecursive(categoriesInCurrCategory.get(curCategoryKey), categoryNodeToAdd);

            curCategoryNode.add(categoryNodeToAdd);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel ClassificationItemInfoLabel;
    private javax.swing.JMenuItem addCategoryItem;
    private javax.swing.JMenuItem addClassItem;
    private javax.swing.JMenuItem addQuestion;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JPopupMenu categoryTreePopupMenu;
    private javax.swing.JTextArea classificationItemInfoTextArea;
    private javax.swing.JTree classificationTree;
    private javax.swing.JMenuItem exit;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JMenuItem helpMenuItem;
    private javax.swing.JLabel includeDetailedAnwersLabel;
    private javax.swing.JLabel includeTipsLabel;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPanel leftPanel;
    private javax.swing.JButton nextQuestionButton;
    private javax.swing.JScrollPane paneWithTree;
    private javax.swing.JButton prevQuestionButton;
    private javax.swing.JMenuBar questionerMenuBar;
    private javax.swing.JLabel questionsCountLabel;
    private javax.swing.JButton quizFinishButton;
    private javax.swing.JCheckBox quizIncludeDetailedAnswersCheckBox;
    private javax.swing.JCheckBox quizIncludeTipsCheckBox;
    private javax.swing.JMenu quizMenu;
    private javax.swing.JTextField quizMinutesTextField;
    private javax.swing.JRadioButton quizNoRadioButton;
    private javax.swing.JPanel quizPanel;
    private javax.swing.JTextPane quizQuestionTextTextPane;
    private javax.swing.JPanel quizQuestionsBrowserPanel;
    private javax.swing.JTextField quizQuestionsCountTextField;
    private javax.swing.JPanel quizReviewPanel;
    private javax.swing.JTextPane quizReviewTextPane;
    private javax.swing.JScrollPane quizScrollPane;
    private javax.swing.JPanel quizSetupPanel;
    private javax.swing.JLabel quizTopicsLabel;
    private javax.swing.JTextPane quizTopicsTextPane;
    private javax.swing.JRadioButton quizVariant0RadioButton;
    private javax.swing.JRadioButton quizVariant1RadioButton;
    private javax.swing.JRadioButton quizVariant2RadioButton;
    private javax.swing.JRadioButton quizVariant3RadioButton;
    private javax.swing.JPanel quizVariantsPanel;
    private javax.swing.JRadioButton quizYesRadioButton;
    private javax.swing.JMenuItem removeCategoryItem;
    private javax.swing.JMenuItem showInfoItem;
    private javax.swing.JButton startQuizButton;
    private javax.swing.JPanel statisticPanel;
    private javax.swing.JLabel timeLabel;
    // End of variables declaration//GEN-END:variables
    private ArrayList<JButton> browseButtons=new ArrayList<JButton>(); // to quick switch between questions
    private ReadWriteClassificationXML reader =new ReadWriteClassificationXML();
    private Classification classification = null;
//    public String classificationXMLPath="D:\\questioner\\data\\classification.xml";
//    public String questionsPath="D:\\questioner\\data\\questions\\";
    public String classificationXMLPath=Config.classificationXMLPath;
    public String dataPath=Config.questionsPath;
    private Random questionerRandom=new Random(new Date().getTime());
    
    private Quiz quiz=null;
    private QuizResult quizResult=null;

        public void addCategoryOrClassToQuiz (ClassificationItem classorcategory , Quiz quiz){

            if(classorcategory instanceof  Category){
                    Category category=(Category)classorcategory;

                if( category.getFileName()!=null ){
                        
                         if(this.quizTopicsTextPane.getText().indexOf(category.toString())<0  && category.getnOfQuestions()>0 ){
                                this.quizTopicsTextPane.setText(this.quizTopicsTextPane.getText()+category+"\n");
                                quiz.getCategories().put(category.getId(), category);
                         }
                }
                
                if(category.getCategories().size()>0    ){
                        Set<String> childCategoriesKeySet=category.getCategories().keySet();
                        for(String item : childCategoriesKeySet){
                            addCategoryOrClassToQuiz(category.getCategories().get(item), quiz);
                        }
                }else return;
            }

              if(classorcategory instanceof  Class){
                    Class currentClass=(Class)classorcategory;
                    if(currentClass.getCategories().size()>0){
                        Set<String> childCategoriesKeySet=currentClass.getCategories().keySet();
                        for(String item : childCategoriesKeySet){
                            addCategoryOrClassToQuiz(currentClass.getCategories().get(item), quiz);
                        }
                    }
              }
    }

        public void runQuiz(){
             this.quizQuestionsBrowserPanel.setLayout(new FlowLayout());
             this.quizQuestionsBrowserPanel.removeAll();
              int questionCount=this.quiz.getQuestions().size();

              this.browseButtons.clear();
              
             for(int i=0;i<questionCount;i++){
                    JButton button=new JButton( (i+1)+"" );
                     this.browseButtons.add(button);
                    final int currQuestionI=i;
                           button.addActionListener(new java.awt.event.ActionListener() {
                             public void actionPerformed(java.awt.event.ActionEvent evt) {
                                 
                                 setCurrentQuestion(currQuestionI);
                                }
                         });

                    this.quizQuestionsBrowserPanel.add(button);
             }

             this.quizScrollPane.setViewportView(this.quizQuestionsBrowserPanel);
             activateDeactivateNextPrevBrowseButtons();
             ShowQuestionAndshowVariants(null);
             return ;
        }

        public void activateDeactivateNextPrevBrowseButtons(){
            if(this.quiz.hasNextQuestion()) this.nextQuestionButton.setEnabled(true);
            else this.nextQuestionButton.setEnabled(false);

            if(this.quiz.hasPreviousQuestion()) this.prevQuestionButton.setEnabled(true);
            else this.prevQuestionButton.setEnabled(false);

            for(int i=0;i<browseButtons.size();i++){
                browseButtons.get(i).setBackground(new Color(212,208,200));
            }
            browseButtons.get(this.quiz.getCurrentQuestionIndex()).setBackground(Color.green);
        }

        public void ShowQuestionAndshowVariants(Question question){
            String questionText="";
            String variants = "" ; //if question type == 0
            if(this.quiz.getCurrentQuestion().getType().equals("0")){
                     questionText=this.quiz.getCurrentQuestion().getQuestionText();
                     // variants with 'tags' like $v1$ and $v1end$
                     String tempVarians=this.quiz.getCurrentQuestion().getQuestionText().substring(
                                this.quiz.getCurrentQuestion().getQuestionText().indexOf("$v$"),
                                this.quiz.getCurrentQuestion().getQuestionText().indexOf("$vend$")
                             );
                    questionText=questionText.substring(0,questionText.indexOf("$v"));
                    for(int i=0;i<10;i++){
                        if(tempVarians.contains("$v"+i+"$")){
                            variants+="\nVariant "+ (i+1) +" :"+tempVarians.substring(
                               tempVarians.indexOf("$v"+i+"$")+4,
                                tempVarians.indexOf("$v"+i+"end$")
                             );
                        }
                    }
            }
            else{
                 questionText=this.quiz.getCurrentQuestion().getQuestionText();
            }

              this.quizQuestionTextTextPane.setText(questionText+"\n"+variants);

              quizPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null,"Quiz :question #"+(quiz.getCurrentQuestionIndex()+1),
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, java.awt.Color.black));


            for(Component comp:this.quizVariantsPanel.getComponents()){
                comp.setVisible(false);
            }

            if(this.quiz.getCurrentQuestion().getType().equals("0")){
              this.quizVariant0RadioButton.setVisible(true);
              this.quizVariant1RadioButton.setVisible(true);
              this.quizVariant2RadioButton.setVisible(true);
              this.quizVariant3RadioButton.setVisible(true);

               this.buttonGroup1.clearSelection();

              if(this.quiz.getAnswers().containsKey(this.quiz.getCurrentQuestion().getId())){

                          if(this.quiz.getAnswers().get(this.quiz.getCurrentQuestion().getId()).equals("0")  ){
                                this.quizVariant0RadioButton.setSelected(true);
                          }

                            if(this.quiz.getAnswers().get(this.quiz.getCurrentQuestion().getId()).equals("1")  ){
                                this.quizVariant1RadioButton.setSelected(true);
                            }
                            if(this.quiz.getAnswers().get(this.quiz.getCurrentQuestion().getId()).equals("2")  ){
                                this.quizVariant2RadioButton.setSelected(true);
                            }
                            if(this.quiz.getAnswers().get(this.quiz.getCurrentQuestion().getId()).equals("3")  ){
                                this.quizVariant3RadioButton.setSelected(true);
                            }
                }
              
            }

            if(this.quiz.getCurrentQuestion().getType().equals("1")){
              this.quizYesRadioButton.setVisible(true);
              this.quizNoRadioButton.setVisible(true);

              this.buttonGroup2.clearSelection();

                            if(this.quiz.getAnswers().containsKey(this.quiz.getCurrentQuestion().getId())){
                                   if(this.quiz.getAnswers().get(this.quiz.getCurrentQuestion().getId()).contains("yes")  ){
                                            this.quizYesRadioButton.setSelected(true);
                                    }
                                     if(this.quiz.getAnswers().get(this.quiz.getCurrentQuestion().getId()).contains("no")  ){
                                            this.quizNoRadioButton.setSelected(true);
                                     }
                            }
            }
        }

        public void saveAnswer(){
            if(this.quiz.getCurrentQuestion().getType().equals("0")){
                    if(this.quizVariant0RadioButton.isSelected())
                        this.quiz.getAnswers().put(this.quiz.getCurrentQuestion().getId(), "0");

                     if(this.quizVariant1RadioButton.isSelected())
                        this.quiz.getAnswers().put(this.quiz.getCurrentQuestion().getId(), "1");

                     if(this.quizVariant2RadioButton.isSelected())
                        this.quiz.getAnswers().put(this.quiz.getCurrentQuestion().getId(), "2");

                     if(this.quizVariant3RadioButton.isSelected())
                        this.quiz.getAnswers().put(this.quiz.getCurrentQuestion().getId(), "3");
            }

            if(this.quiz.getCurrentQuestion().getType().equals("1")){
                if(this.quizYesRadioButton.isSelected())
                    this.quiz.getAnswers().put(this.quiz.getCurrentQuestion().getId(), "yes");
                if(this.quizNoRadioButton.isSelected())
                    this.quiz.getAnswers().put(this.quiz.getCurrentQuestion().getId(), "no");
            }
        }

        public void setCurrentQuestion(int n){
                // n - 0,1,2,...
                saveAnswer();
                this.quiz.setCurrentQuestionIndex(n);

                activateDeactivateNextPrevBrowseButtons();
                ShowQuestionAndshowVariants(null);
        }

        public void showCorrectAndWrongAnswers(QuizResult result){
           this.quizReviewTextPane.setContentType("text/html");

           String quizReviewString="";
           Set<String> items=null;

           quizReviewString+="<b>Quiz review</b><br>";
           quizReviewString+="Quiz with "+result.getTotalQuestions()+" quiestions <br>";
           quizReviewString+=" Correct answers count  <b>"+result.getCorrectAnswers()+"</b> <br>";

           quizReviewString+="<b>Correct answered questions</b><br>";
           quizReviewString+="<p style='background-color:#85BB65'>" ;
           
           items=result.getCorrectQuestions().keySet();

           for(String item:items){
               quizReviewString+=result.getCorrectQuestions().get(item).getQuestionText()+"<br>---<br>";
           }
           quizReviewString+="</p>";

           quizReviewString+="<p style='background-color:#F75D59'>" ;
           quizReviewString+="<b>Wrong answered questions</b><br>";
           items=result.getWrongQuestions().keySet();
           for(String item:items){
               quizReviewString+=result.getWrongQuestions().get(item).getQuestionText()+"<br>---<br>";
           }
            quizReviewString+="</p>";

            this.quizReviewTextPane.setText(quizReviewString);
        }

}